package com.cpr.shop.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.cpr.shop.service.LoginService;
import com.cpr.shop.service.SmsService;
import com.cpr.shop.utils.VerifyCodeUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

import static com.cpr.shop.constant.RedisTimeoutConstant.TIMEOUT_FIVE_MINUTE;
import static com.cpr.shop.constant.UserRedisConstant.USER_LOGIN_CODE;

/**
 * @Author CPR
 * @Create 2025/1/25 20:13
 * @Version 1.0
 * @Description
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private SmsService smsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        String code;
        String userCode = USER_LOGIN_CODE + phone;
        //判断Redis中是否有该"key+phone"对应的验证码
        //有，返回旧验证码
        code = stringRedisTemplate.opsForValue().get(userCode);
        if(code == null || StrUtil.isBlank(code)){
            //没有,生成6位数字验证码
            code = VerifyCodeUtil.generateAlphaNumericCode();
            //存入redis，设置过期时间5分钟
            stringRedisTemplate.opsForValue().set(userCode,code, Duration.ofSeconds(TIMEOUT_FIVE_MINUTE));

        }
        log.info("生成的验证码为:{}", code);
        //使用阿里云短信服务发送验证码
        smsService.sendMessage(phone, code);

        //返回
        log.info("发送成功");
    }
}
